package les.projeto;
import java.util.ArrayList;
import java.util.Calendar;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
public class SingleSemesterView extends Activity{

	private String semesterName = "";
	private String subjectName = "";
	private String oldSubjectName = "";
	private String subjectDescription = "";
	private String subjectTeacher = "";
	private String subjectLocal = "";
	private String[][] aboutSubjects = null;
	private String[] bdTeachers = null;
	private String[] bdLocals = null;
	private String initialDate = "";
	private String endDate = "";
	private String semesterMean = "";
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.single_semester);
	    
	    Intent intent = getIntent();
	    semesterName = intent.getStringExtra("semesterName");
	    initialDate = getIntent().getStringExtra("initialDate");
	    endDate = getIntent().getStringExtra("endDate");
	    semesterMean = getIntent().getStringExtra("mean");

	    try {
	      if (semesterMean.toString().equals(null))
	         semesterMean = "0";
        } catch (Exception NullPointerException) {
            semesterMean = "0";
        }
 
	    TextView screen = (TextView) findViewById(R.id.TextView02);
	    screen.setText(semesterName);
	    
	    TextView semestersMean = (TextView) findViewById(R.id.semesterMean);
	    semestersMean.setText(String.valueOf(semesterMean));
        	    
	    BD bd = new BD();
	    ArrayList<String> profs = bd.getTeachers(this);
	       if (profs.isEmpty())
	            profs.add("Nenhum - -");
		String[][] teachersAux = new String[profs.size()][3];
	    
		bdTeachers = new String[teachersAux.length];
	    for (int i = 0; i < profs.size(); i++) {
			String[] date = profs.get(i).split(" ");
			bdTeachers[i] = date[0];
			
		}
	    
	    ArrayList<String> locais = bd.getLocal(this);
	    if (locais.isEmpty())
	        locais.add("Nenhum - -");
		String[][] localsAux = new String[locais.size()][3];
		bdLocals = new String[localsAux.length];
	    for (int i = 0; i < locais.size(); i++) {
			String[] date = locais.get(i).split(" ");
			bdLocals[i] = date[0] + " " + date[1].replace("-", "");
		}
	    
	    updateListValues();
	    ListView subjects = (ListView)findViewById(R.id.listViewSemesters);
	    subjects.setOnItemClickListener(new OnItemClickListener() {
	    	@Override
	    	public void onItemClick(AdapterView<?> parent, View view,
	    		int position, long id) {
	    		showSubjects(aboutSubjects[position][0], aboutSubjects[position][1],
		    					aboutSubjects[position][2], aboutSubjects[position][3],aboutSubjects[position][4]);
	    	}
	    });
	}
	
	private void updateListValues() {
	    ListView subjects = (ListView)findViewById(R.id.listViewSemesters);

	    BD bd = new BD();
//	    ArrayList<String> subjectsList = bd.getSubjects(this);

	    ArrayList<String> subjectsList = bd.getSubjectsBySemester(this, semesterName);
		aboutSubjects = new String[subjectsList.size()][5];
		
	    for (int i = 0; i < subjectsList.size(); i++) {
			String[] date = subjectsList.get(i).split(" ");
			aboutSubjects[i][0] = date[0];
			aboutSubjects[i][1] = date[1];
			aboutSubjects[i][2] = date[2];
			aboutSubjects[i][3] = date[3];
			aboutSubjects[i][4] = date[5];
		}
	    
	    
	    String[] values = new String[aboutSubjects.length];
	    
	    for (int i = 0; i < values.length; i++) {
	    	float mean = bd.getSubjectMean(this, aboutSubjects[i][0]);
	    	String grade= "";
	    	if (mean > 0){
	    		grade = String.valueOf(mean);
	    	}
			values[i] = aboutSubjects[i][0] + "      " + grade;
		}
	    
	    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
	    		android.R.layout.simple_list_item_1, android.R.id.text1, values);
	    subjects.setAdapter(adapter);
	    subjects.invalidate();
	}

	private void showSubjects(final String name, final String description, final String teacher, final String local, final String credits) {
		Calendar date = Calendar.getInstance();

		int month = date.get(Calendar.MONTH);
        int year = date.get(Calendar.YEAR);
        int today = date.get(Calendar.DATE);
		Intent trocatela = new Intent(SingleSemesterView.this, SubjectsView.class);
	    trocatela.putExtra("date", year+"-"+month+"-"+today);
	   
	    trocatela.putExtra("semesterName", semesterName);
	    trocatela.putExtra("initialDate", initialDate);
	    trocatela.putExtra("endDate", endDate);
	    
	    trocatela.putExtra("subjectName", name);
	    trocatela.putExtra("subjectTeacher", teacher);
	    trocatela.putExtra("subjectPlace", local);
	    trocatela.putExtra("credits", credits);
	    trocatela.putExtra("mean", semesterMean);    
	    SingleSemesterView.this.startActivity(trocatela);
	    SingleSemesterView.this.finish();
		
		}
	
	protected void editSubjectDescription(final String name, String description, final String teacher, final String local) {
		 AlertDialog.Builder helpBuilder = new AlertDialog.Builder(this);
		 helpBuilder.setTitle("Editing subject " + name);
		 helpBuilder.setMessage("Enter the new description of matter: ");
		 final EditText input = new EditText(this);
		 input.setSingleLine();
		 input.setText(description);
		 helpBuilder.setView(input);
	
		 helpBuilder.setPositiveButton("Next", new DialogInterface.OnClickListener() {
			  @Override
			  public void onClick(DialogInterface dialog, int which) {
				  subjectDescription = "";
				  subjectDescription = input.getText().toString();
				  dialog.cancel();
				  editSubjectTeacher(name, teacher , local);
			  }
		 });
		 helpBuilder.setNeutralButton("Cancel", new DialogInterface.OnClickListener() {
		  @Override
		  public void onClick(DialogInterface dialog, int which) {
			  dialog.cancel();
		  }
		 });
		
		 AlertDialog helpDialog = helpBuilder.create();
		 helpDialog.show();
		
	}

	protected void editSubjectTeacher(final String name, final String teacher, final String local) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("Select a teacher");
		
		int selected = -1; // does not select anything
		subjectTeacher = "";
		
		builder.setSingleChoiceItems(bdTeachers, selected, new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				subjectTeacher =  bdTeachers[which];
			}
		});
		
		 builder.setPositiveButton("Save", new DialogInterface.OnClickListener() {
			  @Override
			  public void onClick(DialogInterface dialog, int which) {
				  if (subjectTeacher.trim().isEmpty())
						subjectTeacher = "Nenhum";
				  dialog.cancel();
				  editSubjectLocal(name, local);
			  }
		 });
		 builder.setNeutralButton("Voltar", new DialogInterface.OnClickListener() {
		  @Override
		  public void onClick(DialogInterface dialog, int which) {
			  dialog.cancel();
		  }
		 });
		
		 AlertDialog helpDialog = builder.create();
		 helpDialog.show();
	}
	
	
	protected void editSubjectLocal(final String name, String local) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("Select the new place");
		
		int selected = -1; // does not select anything
		subjectLocal = "";
		
		builder.setSingleChoiceItems(bdLocals, selected, new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				subjectLocal =  bdLocals[which];
			}
		});
	
		builder.setPositiveButton("Next", new DialogInterface.OnClickListener() {
			  @Override
			  public void onClick(DialogInterface dialog, int which) {

					if (subjectLocal.trim().isEmpty())
						subjectLocal = "Nenhum";
				  dialog.cancel();
				  editSubject();
//				  editSubjectTime(name, hour);
			  }
		 });
		builder.setNeutralButton("Back", new DialogInterface.OnClickListener() {
		  @Override
		  public void onClick(DialogInterface dialog, int which) {
			  dialog.cancel();
		  }
		 });
		
		 AlertDialog helpDialog = builder.create();
		 helpDialog.show();
	}
	
	
	protected void editSubjectName(final String name, final String description, final String teacher, final String local) {
		 oldSubjectName = name;
		 AlertDialog.Builder helpBuilder = new AlertDialog.Builder(this);
		 helpBuilder.setTitle("Editing subjetcs" + name);
		 helpBuilder.setMessage("Enter the new subject: ");
		 final EditText input = new EditText(this);
		 input.setSingleLine();
		 input.setText(name);
		 helpBuilder.setView(input);
	
		 helpBuilder.setPositiveButton("Next", new DialogInterface.OnClickListener() {
			  @Override
			  public void onClick(DialogInterface dialog, int which) {
				  subjectName = "";
				  subjectName = input.getText().toString();
				  editSubjectDescription(name, description, teacher, local);
				  dialog.cancel();
			  }
		 });
		 helpBuilder.setNeutralButton("Cancel", new DialogInterface.OnClickListener() {
		  @Override
		  public void onClick(DialogInterface dialog, int which) {
			  dialog.cancel();
		  }
		 });
		
		 AlertDialog helpDialog = helpBuilder.create();
		 helpDialog.show();		
	}

	protected void addNameSubject() {
		 AlertDialog.Builder helpBuilder = new AlertDialog.Builder(this);
		 helpBuilder.setTitle("Add subject");
		 helpBuilder.setMessage("Enter the name subject: ");
		 final EditText input = new EditText(this);
		 input.setSingleLine();
		 input.setText("");
		 helpBuilder.setView(input);
	
		 helpBuilder.setPositiveButton("Next", new DialogInterface.OnClickListener() {
			  @Override
			  public void onClick(DialogInterface dialog, int which) {
				  subjectName = "";
				  subjectName = input.getText().toString();
				  dialog.cancel();
				  addSubjectDescription();
			  }
		 });
		 helpBuilder.setNeutralButton("Back", new DialogInterface.OnClickListener() {
		  @Override
		  public void onClick(DialogInterface dialog, int which) {
			  dialog.cancel();
		  }
		 });
		
		 AlertDialog helpDialog = helpBuilder.create();
		 helpDialog.show();
	}

	protected void addSubjectDescription() {
		 AlertDialog.Builder helpBuilder = new AlertDialog.Builder(this);
		 helpBuilder.setTitle("Add subject");
		 helpBuilder.setMessage("Enter descprition subject: ");
		 final EditText input = new EditText(this);
		 input.setSingleLine();
		 input.setText("");
		 helpBuilder.setView(input);
	
		 helpBuilder.setPositiveButton("Next", new DialogInterface.OnClickListener() {
			  @Override
			  public void onClick(DialogInterface dialog, int which) {
				  subjectDescription = "";
				  subjectDescription = input.getText().toString();
				  dialog.cancel();
				  addSubjectTeacher();
			  }
		 });
		 helpBuilder.setNeutralButton("Back", new DialogInterface.OnClickListener() {
		  @Override
		  public void onClick(DialogInterface dialog, int which) {
			  dialog.cancel();
		  }
		 });
		
		 AlertDialog helpDialog = helpBuilder.create();
		 helpDialog.show();
		
	}
	
	protected void addSubjectTeacher() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("Select a teacher");
		
		int selected = -1; // does not select anything
		subjectTeacher = "";
		
		builder.setSingleChoiceItems(bdTeachers, selected, new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				subjectTeacher =  bdTeachers[which];
			}
		});
		
		 builder.setPositiveButton("Salvar", new DialogInterface.OnClickListener() {
			  @Override
			  public void onClick(DialogInterface dialog, int which) {
				  if (subjectTeacher.trim().isEmpty())
						subjectTeacher = "Nenhum";
				  dialog.cancel();
				  addSubjectLocal();
			  }
		 });
		 builder.setNeutralButton("Back", new DialogInterface.OnClickListener() {
		  @Override
		  public void onClick(DialogInterface dialog, int which) {
			  dialog.cancel();
		  }
		 });
		
		 AlertDialog helpDialog = builder.create();
		 helpDialog.show();
	}

	protected void addSubjectLocal() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("Select a place");
		
		int selected = -1; // does not select anything
		subjectLocal = "";
		
		builder.setSingleChoiceItems(bdLocals, selected, new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				subjectLocal =  bdLocals[which];
			}
		});
	
		builder.setPositiveButton("Save", new DialogInterface.OnClickListener() {
			  @Override
			  public void onClick(DialogInterface dialog, int which) {

					if (subjectLocal.trim().isEmpty())
						subjectLocal = "Nenhum";
				  dialog.cancel();
				  addSubjectInBD();
//				  addSubjectTime();
			  }
		 });
		builder.setNeutralButton("Back", new DialogInterface.OnClickListener() {
		  @Override
		  public void onClick(DialogInterface dialog, int which) {
			  dialog.cancel();
		  }
		 });
		
		 AlertDialog helpDialog = builder.create();
		 helpDialog.show();
	}
	

	protected void addInfoExtra() {
		 AlertDialog.Builder helpBuilder = new AlertDialog.Builder(this);
		 helpBuilder.setTitle("Add extra info");
		 helpBuilder.setMessage("Group of the discipline: ");
		 final EditText input = new EditText(this);
		 input.setSingleLine();
		 input.setText("");
		 helpBuilder.setView(input);
	
		 helpBuilder.setPositiveButton("Next", new DialogInterface.OnClickListener() {
			  @Override
			  public void onClick(DialogInterface dialog, int which) {
				  input.getText().toString();
				  dialog.cancel();
				  addSubjectInfoSite();
			  }
		 });
		 helpBuilder.setNeutralButton("Back", new DialogInterface.OnClickListener() {
		  @Override
		  public void onClick(DialogInterface dialog, int which) {
			  dialog.cancel();
		  }
		 });
		
		 AlertDialog helpDialog = helpBuilder.create();
		 helpDialog.show();
		
	}
	
	protected void addSubjectInfoSite() {
		 AlertDialog.Builder helpBuilder = new AlertDialog.Builder(this);
		 helpBuilder.setTitle("Add extra info");
		 helpBuilder.setMessage("Site of the discipline: ");
		 final EditText input = new EditText(this);
		 input.setSingleLine();
		 input.setText("");
		 helpBuilder.setView(input);
	
		 helpBuilder.setPositiveButton("Next", new DialogInterface.OnClickListener() {
			  @Override
			  public void onClick(DialogInterface dialog, int which) {
				  input.getText().toString();
				  dialog.cancel();
				  addSubjectInfoObs();
			  }
		 });
		 helpBuilder.setNeutralButton("Back", new DialogInterface.OnClickListener() {
		  @Override
		  public void onClick(DialogInterface dialog, int which) {
			  dialog.cancel();
		  }
		 });
		
		 AlertDialog helpDialog = helpBuilder.create();
		 helpDialog.show();
		
	}
	
	protected void addSubjectInfoObs() {
		 AlertDialog.Builder helpBuilder = new AlertDialog.Builder(this);
		 helpBuilder.setTitle("Add extra info");
		 helpBuilder.setMessage("Observations: ");
		 final EditText input = new EditText(this);
		 input.setSingleLine();
		 input.setText("");
		 helpBuilder.setView(input);
	
		 helpBuilder.setPositiveButton("Next", new DialogInterface.OnClickListener() {
			  @Override
			  public void onClick(DialogInterface dialog, int which) {
				  input.getText().toString();
				  dialog.cancel();
				  addSubjectInfoExtraInBD();
				  addSubjectInBD();
			  }
		 });
		 helpBuilder.setNeutralButton("Back", new DialogInterface.OnClickListener() {
		  @Override
		  public void onClick(DialogInterface dialog, int which) {
			  dialog.cancel();
		  }
		 });
		
		 AlertDialog helpDialog = helpBuilder.create();
		 helpDialog.show();
		
	}

	protected void addSubjectInfoExtraInBD() {
//	    BD bd = new BD();
//	    bd.insertSubjectInfo(this, subjectName, subjectInfoGroup, subjectInfoSite, subjectInfoObs);
//	    startActivity(getIntent()); 
//	    finish();
	}


	protected void addSubjectInBD() {
	    BD bd = new BD();
	    bd.insertSubject(this, subjectName, subjectDescription, subjectTeacher, subjectLocal, semesterName, 0, 0);
	    updateListValues();
	}   
	
	protected void editSubject(){
		BD bd = new BD();
		bd.editSubject(this, oldSubjectName, subjectName, subjectDescription, subjectTeacher, subjectLocal);
	    updateListValues();
	}
		
	@Override
	public void onBackPressed() {
		
        back();	        		 
        return;
	}
	
	private void back() {
		Calendar date = Calendar.getInstance();

		int month = date.get(Calendar.MONTH);
        int year = date.get(Calendar.YEAR);
        int today = date.get(Calendar.DATE);
        
        Intent trocatela = new Intent(SingleSemesterView.this, SemestersView.class);
    	trocatela.putExtra("date", year+"-"+month+"-"+today);
    	
    	SingleSemesterView.this.startActivity(trocatela);
    	SingleSemesterView.this.finish();	 
	}

    private void editSemester() {
        Calendar calendar = Calendar.getInstance();
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        int month = calendar.get(Calendar.MONTH);
        int year = calendar.get(Calendar.YEAR);
        
        Intent intent = new Intent(SingleSemesterView.this,EditSemesterView.class);
        intent.putExtra("date", year+"-"+month+"-"+day);
        intent.putExtra("semesterName", semesterName);
        intent.putExtra("initialDate", initialDate);
        intent.putExtra("endDate", endDate);
        SingleSemesterView.this.startActivity(intent);
        SingleSemesterView.this.finish();
    }

    private void addSemester() {
        addNameSubject();
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
     super.onCreateOptionsMenu(menu);
     menu.add(0,0,0,"Add subject");
     menu.add(1,1,1,"Edit semester");
     return true;
    } 
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
         super.onOptionsItemSelected(item);
         switch (item.getItemId()) {
            case 0:
                addSemester();
                break;
            case 1:
                editSemester();
                break;
         }
         return false;
    } 
}
